import os
import queue
import time
from threading import Thread, active_count, current_thread, Lock

# def task(name):
#     print('%s is running' % name)
#     time.sleep(2)
#     print('%s is done' % name)


# if __name__ == '__main__':
#     t = Thread(target=task, args=('线程1',))
#     # 造线程非常快，因为不用开辟空间了
#     t.start()
#     print('主')

n = 100

# def task():
#     global n
#     print('%s is running' % os.getpid())
#     print('子%s' % current_thread().name)
#     n = 0
#     time.sleep(3)
#
#
# if __name__ == '__main__':
#     t_arr = []
#     for i in range(1, 5):
#         t = Thread(target=task)
#         t_arr.append(t)
#         # 开启子线程
#         t.start()
#         # 线程的个数
#     print("===============\n", active_count(), "================\n")
#     for t in t_arr:
#         # 等待子线程运行完
#         t.join()
#     # 线程所在的进程pid
#     print('主%s' % os.getpid())
#     # 线程的名字
#     print('主%s' % current_thread().name)
#     # 同一个进程的所有线程资源共享
#     print(n)


mutex = Lock()


# def task():
#     global n
#     # 线程1加锁
#     mutex.acquire()
#     temp = n
#     # 在这个时间消耗完之前，后面的99个线程都进来了
#     # 并且拿到的是temp=100
#     # 效率高了，不安全
#     # IO操作切换线程
#     time.sleep(0.1)
#     print(n)
#
#     n = temp - 1
#     # 线程1计算完成释放锁
#     mutex.release()
#
#
# if __name__ == '__main__':
#     t_l = []
#     start = time.time()
#     for i in range(100):
#         t = Thread(target=task)
#         t_l.append(t)
#         t.start()
#     for t in t_l:
#         t.join()
#     print(n, time.time() - start)


def producer(name, food, q):
    for i in range(10):
        res = '%s%s' % (food, i)
        # 模拟生产数据的时间
        time.sleep(3)
        q.put(res)
        print('厨师%s生产了%s' % (name, res))


def consumer(name, q):
    while True:
        # 订单都没来还在等呢
        # 生产者往消费者发信号
        res = q.get()
        # 第十个是一个空
        if res is None:
            #  主线程和最后一个线程
            # if active_count() is 2:
            if active_count() == 2:
                print(time.time() - start)

            break
        # 模拟处理数据的时间
        time.sleep(3)
        print('吃货%s吃了%s' % (name, res))


if __name__ == '__main__':
    start = time.time()
    q = queue.Queue()
    # 生产者
    p1 = Thread(target=producer, args=('大海', '包子', q))
    p2 = Thread(target=producer, args=('中海', '辣椒炒肉', q))
    p3 = Thread(target=producer, args=('小海', '土豆丝', q))
    # 消费者
    c1 = Thread(target=consumer, args=('夏洛', q))
    c2 = Thread(target=consumer, args=('西施', q))
    # 生产者和消费者并发
    p1.start()
    p2.start()
    p3.start()
    c1.start()
    c2.start()
    # 生产完了
    p1.join()
    p2.join()
    p3.join()
    # 发结束信号给消费者
    # 发送给队列一个None
    q.put(None)
    q.put(None)
    print('主')
